import { defineStore } from "pinia";
import { ref, computed } from "vue";
import { useUserStore } from "./userStore";
import { insertCartAPI, findNewCartListAPI, deleteCartAPI } from "@/apis/cart";
export const useCartStore = defineStore(
  "cart",
  () => {
    const userStore: any = useUserStore();
    const isLogin = computed(() => userStore.userInfo.token);

    const cartList = ref<any>([]);

    // 添加购物车
    const addCart = async (goods: any) => {
      const { skuId, count } = goods;

      if (isLogin.value) {
        await insertCartAPI({ skuId, count });
        updateNewList();
      } else {
        const item = cartList.value.find((item: any) => item.skuId === goods.skuId);
        if (item) {
          item.count++;
        } else {
          cartList.value.push(goods);
        }
      }
    };

    const updateNewList = async () => {
      const res: any = await findNewCartListAPI();
      cartList.value = res.result;
    };

    // 单选功能
    const singleCheck = (skuId: any, selected: any) => {
      const item = cartList.value.find((item: any) => item.skuId === skuId);
      item.selected = selected;
    };

    // 全选功能
    const allCheck = (selected: any) => {
      cartList.value.forEach((item: any) => (item.selected = selected));
    };

    // 删除购物车
    const delCart = async (skuId: any) => {
      if (isLogin.value) {
        await deleteCartAPI([skuId]);
        updateNewList();
      } else {
        const idx = cartList.value.findIndex((item: any) => item.skuId == skuId);
        cartList.value.splice(idx, 1);
      }
    };

    // 清除购物车
    const clearCart = () => {
      cartList.value = [];
    }

    // 计算属性
    const allCount = computed(() => cartList.value.reduce((a: any, c: any) => a + c.count, 0));
    const allPrice = computed(() =>
      cartList.value.reduce((a: any, c: any) => a + c.count * c.price, 0)
    );
    const selectedCount = computed(() => {
      return cartList.value
        .filter((item: any) => item.selected)
        .reduce((a: any, c: any) => a + c.count, 0);
    });

    const selectedPrice = computed(() => {
      return cartList.value
        .filter((item: any) => item.selected)
        .reduce((a: any, c: any) => a + c.count * c.price, 0);
    });
    // 是否全选
    const isAll = computed(() => cartList.value.every((item: any) => item.selected));

    return {
      cartList,
      addCart,
      delCart,
      allCount,
      allPrice,
      singleCheck,
      isAll,
      allCheck,
      selectedCount,
      selectedPrice,
      clearCart,
      updateNewList
    };
  },
  {
    persist: true,
  }
);
